package com.karson.admin.config.satoken;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.karson.common.constants.SAConstants;
import com.karson.common.model.SystemAdmin;
import com.karson.common.model.SystemRole;
import com.karson.service.service.SystemAdminService;
import com.karson.service.service.SystemRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private SystemRoleService systemRoleService;
    @Autowired
    private SystemAdminService systemAdminService;
    // 返回一个账号所拥有的权限码集合
    @Override
    @SuppressWarnings("unchecked")
    public List<String> getPermissionList(Object loginId, String loginType) {

        // 1. 声明权限码集合
        List<String> list = new ArrayList<>();

        // 2. 遍历角色列表，查询拥有的权限码
        for (String roleId : getRoleList(loginId, loginType)) {
            List<String> permissionList = (List<String>)SaManager.getSaTokenDao().getObject(SAConstants.SATOKEN_FIND_PERMS + roleId);
            if(permissionList == null) {
                // 从数据库查询这个角色 id 所拥有的权限列表
                permissionList = systemRoleService.getPremissionList(roleId);
                // 查好后，set 到缓存中
                SaManager.getSaTokenDao().setObject(SAConstants.SATOKEN_FIND_PERMS + roleId, permissionList, 60 * 60 * 24 * 30);
            }
            list.addAll(permissionList);
        }

        // 3. 返回权限码集合
        return list;
    }

    // 返回一个账号所拥有的角色标识集合
    @Override
    @SuppressWarnings("unchecked")
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roleList = (List<String>) SaManager.getSaTokenDao().getObject(SAConstants.SATOKEN_FIND_ROLES + loginId);
        if(roleList == null) {
            // 从数据库查询这个账号id拥有的角色列表，
            LambdaQueryWrapper<SystemAdmin> adminWrapper = new LambdaQueryWrapper<>();
            adminWrapper.select(SystemAdmin::getRoles);
            adminWrapper.eq(SystemAdmin::getId, String.valueOf(loginId));
            SystemAdmin adminRoles = systemAdminService.getOne(adminWrapper);
            String roles = adminRoles.getRoles();
            roleList = List.of(roles.split(","));
            log.info("这是角色列表：{}", roleList);
            // 查好后，set 到缓存中
            SaManager.getSaTokenDao().setObject(SAConstants.SATOKEN_FIND_ROLES + loginId, roleList, 60 * 60 * 24 * 30);
        }
        return roleList;
    }
    
}